<script setup>
import { ref, provide } from 'vue'
import { onLaunch } from '@dcloudio/uni-app'
import { usePlayerStore } from '@/stores/player'
import { createPlayer } from '@/common/player'

// 获取播放器数据和方法
const playerStore = usePlayerStore()

// 导航栏高度
const navBarHeight = ref(0)

// 设置模态框状态
const modal = ref({
  status: {
    mode: 0, // 0-清空，1-删除
    type: 0, // 0-播放，1-收藏歌曲，2-收藏歌单
    showModal: false,
    confirmText: '清空',
    modalTitle: '清空播放队列?',
    content: '',
  },
  confirm: () => {},
})

// 记录滚动位置
let lastScrollTop = 0

// 更新Modal配置
const updateModal = (status) => {
  modal.value = Object.assign({}, modal.value, status)
}

// 更新导航栏高度
const updateNavBarHeight = (height) => {
  navBarHeight.value = height
}

// 滚动时触发
const handleScroll = (e) => {
  let scrollTop = e.detail.scrollTop

  if (playerStore.playerInfo?.id) {
    // 判断向上还是向下
    if (scrollTop > lastScrollTop) {
      // 隐藏小播放器界面
      if (playerStore.playerStatus.smallPlayer)
        playerStore.setPlayerStatus({ smallPlayer: false })
    } else {
      if (!playerStore.playerStatus.smallPlayer)
        playerStore.setPlayerStatus({ smallPlayer: true })
    }
  }

  // 记录滚动位置
  lastScrollTop = scrollTop
}

// 传递滚动方法
provide('common', {
  navBarHeight,
  modal,
  updateModal,
  updateNavBarHeight,
  handleScroll,
})

/**
 * 初始化播放器
 */
const initPlayer = () => {
  // 初始化音频
  createPlayer()

  // 音频播放事件
  uni.$on('onPlay', () => playerStore.setSongPlayStatus(true))

  // 音频暂停事件
  uni.$on('onPause', () => playerStore.setSongPlayStatus(false))

  // 音频进入可以播放状态，但不保证后面可以流畅播放
  uni.$on('onCanplay', (player) => {
    playerStore.setLoading(false)
    playerStore.setPlayerStatus({ duration: player.duration || 0 })
  })

  // 音频自然播放结束事件
  uni.$on('onEnded', () => playerStore.setPlayerNext())

  // 音频上一首事件
  uni.$on('onPrev', () => playerStore.setPlayerPrev())

  // 音频下一首事件
  uni.$on('onNext', () => playerStore.setPlayerNext())

  // 音频播放进度更新事件
  uni.$on('onTimeUpdate', (player) => {
    let percent = (player.currentTime / player.duration) * 100 || 0
    let buffered = (player.buffered / player.duration) * 100 || 0

    playerStore.setPlayerStatus({
      currentTime: player.currentTime,
      duration: player.duration,
      percent: Number(percent.toFixed(2)),
      buffered: Number(buffered.toFixed(2)),
    })
  })

  // 音频加载完成事件
  uni.$on('onWaiting', (player) => {
    playerStore.setLoading(false)
    playerStore.setPlayerStatus({
      currentTime: player.currentTime || 0,
      duration: player.duration || 0,
    })
  })

  // 音频播放错误事件
  uni.$on('onError', () => {
    playerStore.setLoading(false)
    uni.$u.toast('加载音频失败~')
    playerStore.setPlayerNext()
  })
}

onLaunch(() => initPlayer())
</script>

<style lang="scss">
/*每个页面公共css */
@import '@/components/vk-uview-ui/index.scss';
@import '@/static/common/common.scss';
</style>
